package com.verify.web;

import com.verify.emun.ExcelVerifyMethod;
import com.verify.util.R;
import com.verify.resp.ResponseAdvice;
import com.verify.service.ExcelVerifyService;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Map;

@ResponseAdvice
@RestController
@RequiredArgsConstructor
public class ExcelVerifyController {

    private final ExcelVerifyService excelVerifyService;

    @Value("${spring.pre-file}")
    private String fileDirectory;

    //tableName 参考枚举 ExcelVerifyMethod
    @PostMapping("/verify/{tableName}")
    public R verifyFile(
            @PathVariable ExcelVerifyMethod tableName,
            @RequestParam("file") MultipartFile file,
            @RequestParam Map<String, String> params
    ) {
        return tableName.execute(excelVerifyService, convertMultipartFileToFile(file),params);
    }

    @SneakyThrows
    public File convertMultipartFileToFile(MultipartFile multipartFile) {
        // 创建目标文件路径，使用配置的目录和原始文件名
        File file = new File(fileDirectory + "/" + multipartFile.getOriginalFilename());

        // 如果文件目录不存在，则创建该目录
        File parentDir = file.getParentFile();
        if (!parentDir.exists()) {
            parentDir.mkdirs();
        }

        // 将 MultipartFile 转换为 File
        try (FileOutputStream fileOutputStream = new FileOutputStream(file)) {
            fileOutputStream.write(multipartFile.getBytes());
        }

        return file;
    }
}
